﻿using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using LimaLims.Application.Service.Base.Dto;
using LimaLims.Application.Service.Basic.Dto;
using LimaLims.Application.Service.Equipment;
using LimaLims.Application.Service.Equipment.Dto;
using LimaLims.Core;
using LimaLims.Core.Entity.Basic;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace LimaLims.Application.Service.Basic
{
    /// <summary>
    /// 供应商服务
    /// </summary>
    [ApiDescriptionSettings(Name = "Supplier", Order = 167)]
    [Route("api")]
    public class SupplierService : ISupplierService, IDynamicApiController, ITransient
    {
        private readonly IRepository<Supplier> _supplierRep;  // 供应商表仓储
        private readonly IRepository<Material> _materialRep;  // 供应商表仓储

        public SupplierService(IRepository<Supplier> supplier, IRepository<Material> materialRep)
        {
            _supplierRep = supplier;
            _materialRep = materialRep;
        }

        /// <summary>
        /// 新增
        /// </summary>
        [HttpPost("supplier/add")]
        public async Task Add(AddSupplierInput input)
        {
            var isExist = await _supplierRep.DetachedEntities.AnyAsync(u => u.Name == input.Name);
            if (isExist)
                throw Oops.Oh("已存在相同名称的厂家");

            var supplier = input.Adapt<Supplier>();

            await supplier.InsertAsync();
        }

        [HttpPost("supplier/delete")]
        public async Task Delete(long id)
        {
            var supplier = await _supplierRep.DetachedEntities.Include(s => s.Materials).FirstOrDefaultAsync(u => u.Id == id);
            if (supplier == null)
                throw Oops.Oh("不存在此数据");

            if (supplier.Materials.Any())
            {
                throw Oops.Oh("当前供应商下拥有物料信息，请勿直接删除！");
            }

            await supplier.DeleteAsync();
        }

        [HttpGet("supplier/detail")]
        public async Task<Supplier> Detail(long id)
        {
            var supplier = await _supplierRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == id);
            if (supplier == null)
                throw Oops.Oh("不存在此数据！");
            return supplier;
        }

        [HttpPost("supplier/edit")]
        public async Task Edit(EditSupplierInput input)
        {
            var supplier = await _supplierRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id);
            if (supplier == null)
                throw Oops.Oh("不存在此数据！");

            var isExist = await _supplierRep.DetachedEntities.AnyAsync(u => u.Name == input.Name && u.Id != input.Id);
            if (isExist)
                throw Oops.Oh("已存在相同名称的供应商");

            var supplierModel = input.Adapt<Supplier>();

            await supplierModel.UpdateAsync();
        }

        /// <summary>
        /// 下拉数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("supplier/selectList")]
        public async Task<List<SelectDto>> SelectList()
        {
            var list = await _supplierRep.DetachedEntities.Where(s => s.ValidStatus).OrderBy(s => s.Sort).ToListAsync();
            return list.Select(x => new SelectDto
            {
                Value = x.Id,
                Label = x.Name
            }).ToList();
        }

        [HttpGet("supplier/page")]
        public async Task<PageResult<SupplierOutput>> QueryPage([FromQuery] SupplierPageInput input)
        {
            var name = !string.IsNullOrEmpty(input.SearchValue?.Trim());
            var phone = !string.IsNullOrEmpty(input.Phone?.Trim());
            var equipmentFactorys = await _supplierRep.DetachedEntities
                                         .Where((name, u => EF.Functions.Like(u.Name, $"%{input.SearchValue.Trim()}%")))
                                         .Where((phone, u => EF.Functions.Like(u.Phone, $"%{input.Phone.Trim()}%")))
                                         .Where(input.ValidStatus.HasValue, u => u.ValidStatus == input.ValidStatus)
                                         .OrderBy(u => u.Sort)
                                         .Select(u => new SupplierOutput
                                         {
                                             Id = u.Id,
                                             Name = u.Name,
                                             ContactName = u.ContactName,
                                             Level = u.Level,
                                             Phone = u.Phone,
                                             Address = u.Address,
                                             Remark = u.Remark,
                                             ValidStatus = u.ValidStatus,
                                             Sort = u.Sort,
                                             CreatedTime = u.CreatedTime,
                                             CreatedUserName = u.CreatedUserName,
                                             UpdatedTime = u.UpdatedTime,
                                             UpdatedUserName = u.UpdatedUserName
                                         }).ToADPagedListAsync(input.PageNo, input.PageSize);

            return equipmentFactorys;
        }
    }
}
